import { useMemoizedFn, useUpdate } from 'ahooks';
import { Button, Modal } from 'antd';
import React, { useEffect, useMemo, useRef, useState } from 'react';

import './styles.scss';

import { t } from '@/locales/i18n';
import { SvgIcon } from '@/components/icon';
// TODO 这个有bug需要修复，暂时先这样
export const useConfirm = (props?: {
  title?: string;
  iconSrc?: string | '';
  content?: string;
  showCancel?: boolean;
  showClose?: boolean;
  type?: 'common' | 'delete';
  hideFooter?: boolean;
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const update = useUpdate();

  const map = useMemo(() => {
    const map = {
      common: {
        title: t('common.confirm.Common Tip'),
        variant: 'primary',
        iconSrc: 'warning',
      },
      delete: {
        title: t('common.Delete Warning'),
        variant: 'dangerFill',
        iconSrc: 'warning',
      },
    };
    if (props?.type && map[props.type]) return map[props.type];
    return map.common;
  }, [props?.type]);

  const {
    title = map?.title || t('Warning'),
    iconSrc = map?.iconSrc,
    content,
    showCancel = true,
    showClose = true,
    hideFooter = false,
  } = props || {};
  const [customContent, setCustomContent] = useState<string | React.ReactNode>(content);
  const confirmCb = useRef<Function>();
  const cancelCb = useRef<any>();

  const onOpen = () => {
    setIsOpen(true);
    update();
  };

  const onClose = () => {
    setIsOpen(false);
    update();
  };

  const openConfirm = useMemoizedFn(
    (confirm?: Function, cancel?: any, customContent?: string | React.ReactNode) => {
      confirmCb.current = confirm;
      cancelCb.current = cancel;

      customContent && setCustomContent(customContent);

      return onOpen;
    },
  );

  const ConfirmModal = useMemoizedFn(
    ({
      closeText = t('common.Cancel'),
      confirmText = t('common.Confirm'),
      isLoading,
      bg,
      countDown = 0,
    }: {
      closeText?: string;
      confirmText?: string;
      isLoading?: boolean;
      bg?: string;
      countDown?: number;
    }) => {
      const timer = useRef<any>();
      const [countDownAmount, setCountDownAmount] = useState(countDown);
      const [requesting, setRequesting] = useState(false);

      useEffect(() => {
        if (isOpen) {
          setCountDownAmount(countDown);
          timer.current = setInterval(() => {
            setCountDownAmount((val) => {
              if (val <= 0) {
                clearInterval(timer.current);
              }
              return val - 1;
            });
          }, 1000);

          return () => {
            clearInterval(timer.current);
          };
        }
      }, [countDown]);

      return (
        <Modal
          open={isOpen}
          className="eai-confirm-modal"
          onCancel={onClose}
          closable={showClose}
          footer={null}
          width={480}
        >
          <div className="flex flex-col">
            <div className="flex flex-col p-5">
              <div className="flex items-center gap-2 text-base">
                <SvgIcon icon={iconSrc} size={20} color="var(--orange-6)" />
                <span className="text-text-5" style={{ fontWeight: 700 }}>
                  {title}
                </span>
              </div>
              <div className="ml-7 pt-4 text-sm text-text-4">{customContent}</div>
            </div>
            {!hideFooter && (
              <div className="flex w-full border-t-[1px] border-line-2 pb-3">
                <div className="ml-auto pr-4 pt-3">
                  {showCancel && (
                    <Button
                      className="w-[80px] px-5"
                      onClick={() => {
                        onClose();
                        typeof cancelCb.current === 'function' && cancelCb.current();
                      }}
                    >
                      {closeText}
                    </Button>
                  )}

                  <Button
                    type="primary"
                    className="ml-2 w-[80px] px-5"
                    disabled={countDownAmount > 0}
                    loading={isLoading || requesting}
                    onClick={async () => {
                      setRequesting(true);
                      try {
                        typeof confirmCb.current === 'function' && (await confirmCb.current());
                        onClose();
                      } catch (error) {}
                      setRequesting(false);
                    }}
                  >
                    {countDownAmount > 0 ? `${countDownAmount}s` : confirmText}
                  </Button>
                </div>
              </div>
            )}
          </div>
        </Modal>
      );
    },
  );

  return {
    openConfirm,
    onClose,
    ConfirmModal,
  };
};
